package com.CmJava.serviceImpl;

import com.CmJava.entity.Message;
import com.CmJava.entity.MessageList;
import com.CmJava.service.MessageService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private RedisTemplate redisTemplate;

    private static final SimpleDateFormat SIMPLE_DATE_FORMAT=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public boolean saveMessage(String userName,String friendName, String message, String time,int num) {
        String redisKey="message_"+userName+"_to_"+friendName+"_for_ChatRoom";
        Message message1;
        if (num==0){
//            num==0：来自用户的信息
            message1 = new Message(userName, message, time);
        }else {
//            num==1：来自好友的信息
            message1 = new Message(friendName, message, time);
        }

        MessageList messageList;
        try {

            if (redisTemplate.hasKey(redisKey)) {
                messageList = (MessageList) redisTemplate.opsForValue().get(redisKey);
                messageList.getMessages().add(message1);

            }else {
                ArrayList<Message> messages = new ArrayList<>();
                messages.add(message1);
                messageList = new MessageList(friendName, messages, SIMPLE_DATE_FORMAT.format(new Date()));
            }
            redisTemplate.opsForValue().set(redisKey,messageList);
        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Override
    public List<MessageList> getMessage(String userName, String friendList) {
        String redisKey="";
        ArrayList<MessageList> messageLists = new ArrayList<>();
        for (String friendName : friendList.split(",")) {
            redisKey="message_"+userName+"_to_"+friendName+"_for_ChatRoom";
            if (!redisTemplate.hasKey(redisKey)) {
                messageLists.add(null);
            }else {
                MessageList messageList = (MessageList) redisTemplate.opsForValue().get(redisKey);
                messageLists.add(messageList);
            }
        }
        return messageLists;

    }
}
